<?php


namespace app\admin\service;

use app\common\enum\MainEnum;
use app\common\exception\ForbiddenException;
use app\common\exception\ParameterFailedException;
use app\common\model\AppTokenModel;
use app\common\model\UserModel;
use app\common\model\UserPlatformTokenModel;
use app\common\service\WarmUpCache;

class RbacService
{
    public static $user_id;

    /**
     * 检查权限
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020-09-23
     * @Time: 19:36
     */
    public static function checkPermissions()
    {
//        //检测token是否有效
//        $header = request()->header();
//        $key    = 'access-token';
//        if (!isset($header[$key])) {
//            throw new ForbiddenException(
//                [
//                    'msg'  => '请输入令牌',
//                    'code' => MainEnum::ERROR_TOKEN_NEED,
//                ]
//            );
//        }
//        $accessToken   = $header[$key];
//        $appTokenModel = (new AppTokenModel())->where('app', App('http')->getName())->where(
//            'access_token',
//            $accessToken
//        )->find();
//        if (!$appTokenModel) {
//            throw new ForbiddenException(
//                [
//                    'msg'  => '令牌有误',
//                    'code' => MainEnum::ERROR_TOKEN_ERROR,
//                ]
//            );
//        }
//        if (strtotime($appTokenModel->getData('expire_time')) - NOW_TIME < 0) {
//            throw new ForbiddenException(
//                [
//                    'msg'  => '令牌已过期',
//                    'code' => MainEnum::ERROR_TOKEN_EXPIRE,
//                ]
//            );
//        }
//        $userId = $appTokenModel->getData('user_id');
//        //获取用户group_id
//        $userModel = UserModel::where('id', $userId)->find();
//        if (!$userModel) {
//            throw new ForbiddenException(
//                [
//                    'msg'  => '用户不存在',
//                    'code' => MainEnum::ERROR_TOKEN_ERROR,
//                ]
//            );
//        }
//        #给token续时
//        $appTokenModel->expire_time = NOW_TIME + MainEnum::APP_TOKEN_EXPIRE_TIMESTAMP;
//        $appTokenModel->save();
////
////        $app        = App('http')->getName();
////        $controller = request()->controller();
////        $action     = request()->action();
////        $method     = request()->method();
////        //var_dump($app,$controller,$action,$method);die;
////        //user_id => group_id => role_ids
////        $groupRoles   = self::getRBACGroupRole();
////        $needRolesIds = [];
////        foreach ($groupRoles as $groupRole) {
////            #筛选出这个组的所有权限
////            if ($groupRole['group_id'] == $userModel->getData('group_id')) {
////                $needRolesIds[] = (int)$groupRole['role_id'];
////                $ownRole[]      = $groupRole;
////            }
////        }
////        $pass    = false;
////        $roles   = self::getRBACRole();
////        $ownRole = [];#用户拥有的所有权限集合
////
////        foreach ($roles as $role) {
////            if ($role['common'] === '是') {
////                $ownRole[] = $role;
////                $pass      = true;
////                continue;
////            }
////            foreach ($needRolesIds as $needRoleId) {
////                //筛选组内权限，如果是公共权限则跳过
////                if ($needRoleId === $role['id']) {
////                    //公共权限 || 有权 => 放权
////                    if (strtolower($role['app']) === strtolower($app) && strtolower($role['controller']) === strtolower(
////                            $controller
////                        ) && strtolower($role['action']) === strtolower($action) && strtolower(
////                            $role['method']
////                        ) === strtolower($method)) {
////                        $ownRole[] = $role;
////                        $pass      = true;
////                    }
////                }
////            }
////        }
////        if (!$pass) {
////            throw new ForbiddenException();
////        }
//
//        return [
//            'user_info' => $userModel->getData(),
//            'roles'     => $ownRole,
//        ];
    }

    public static function getRbacGroup()
    {
        //缓存中没有，从mysql中读取
        //$data = Redis::tableGet('group');
        //if (!$data) {
        return WarmUpCache::group();
        //}
        //return $data;
    }

    public static function getRBACRole()
    {
        //缓存中没有，从mysql中读取
        //$data = Redis::tableGet('role');
        //if (!$data) {
        return WarmUpCache::role();
        //}
        //return $data;
    }

    public static function getRBACGroupRole()
    {
        //缓存中没有，从mysql中读取
        //$data = Redis::tableGet('group_role');
        //if (!$data) {
        return WarmUpCache::group_role();
        //}
        //return $data;
    }

    public static function setToken($user_id, $platform_specific = 'Admin'): string
    {
        $accessToken   = getToken();
        $appTokenModel = (new UserPlatformTokenModel())->where('platform_specific', $platform_specific)->where(
            'user_id',
            $user_id
        )->find();
        $expire_time   = NOW_TIME + MainEnum::APP_TOKEN_EXPIRE_TIMESTAMP;
        if (!$appTokenModel) {
            (new UserPlatformTokenModel())->save(
                [
                    'platform_specific' => $platform_specific,
                    'access_token'      => $accessToken,
                    'user_id'           => $user_id,
                    'expire_time'       => $expire_time,
                ]
            );
        }
        else {
            $appTokenModel->access_token = $accessToken;
            $appTokenModel->expire_time  = $expire_time;
            $appTokenModel->save();
        }
        return $accessToken;
    }
}